﻿using System;
using System.Web.Script.Serialization;
using Splendor_Server.script.net;

public class MsgBase
{
    //协议名
    public string protoName = "null";

    //编码器
    private static JavaScriptSerializer Js = new JavaScriptSerializer();

    //协议体编码
    public static byte[] Encode(MsgBase msgBase)
    {
        //JsonUtility.ToJson将协议体msgBase转成字符串
        //System.Text.Encoding.UTF8.GetBytes将字符串转成byte[]
        return System.Text.Encoding.UTF8.GetBytes(Js.Serialize(msgBase));
    }

    //协议体解码
    public static MsgBase Decode(string protoName, byte[] bytes, int offset, int count)
    {
        //System.Text.Encoding.UTF8.GetString将byte数组中的部分数据解析成字符串
        //Type.GetType获取协议名对应的类型
        //JsonUtility.FromJson将字符串还原成指定类型的协议对象
        string format = System.Text.Encoding.UTF8.GetString(bytes, offset, count);
        Console.WriteLine("[{0}]Receive: {1}", NetManager.GetNowTime(), format);
        return (MsgBase) Js.Deserialize(format, Type.GetType(protoName));
    }

    //协议名编码 2+协议名长度
    public static byte[] NameEncode(MsgBase msgBase)
    {
        byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(msgBase.protoName);
        Int16 length = (Int16) nameBytes.Length;
        //长度以小端编码形式
        byte[] bytes = new byte[2 + length];
        bytes[0] = (byte) (length % 256);
        bytes[1] = (byte) (length / 256);
        Array.Copy(nameBytes, 0, bytes, 2, length);
        return bytes;
    }

    //协议名解码
    public static string NameDecode(byte[] bytes, int offset, out int count)
    {
        count = 0;
        //数据必须大于2字节
        if (offset + 2 > bytes.Length)
        {
            return "";
        }

        Int16 length = (Int16) ((bytes[offset + 1] << 8) | bytes[offset]);

        //数据必须大于长度+2
        if (length <= 0 || offset + 2 + length > bytes.Length)
        {
            return "";
        }

        count = 2 + length;
        return System.Text.Encoding.UTF8.GetString(bytes, offset + 2, length);
    }
}